package soulkun.library.mvvm.component

import android.content.Context
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import soulkun.library.utils.log.LogUtils
import java.lang.NullPointerException

abstract class BaseDataBindingActivity<Binding : ViewDataBinding>(private val isNeedLogLifecycle: Boolean = false) :
    AppCompatActivity() {

    companion object {
        private const val TAG = "BaseDataBindingActivity"
    }

    private var mBinding: Binding? = null
    protected lateinit var mContext: Context
    protected lateinit var mActivity: AppCompatActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onCreate")
        mBinding = DataBindingUtil.setContentView(this, setLayout())
        mBinding!!.lifecycleOwner = this
        mContext = this
        mActivity = this
        initIntent(savedInstanceState)
        initView()
        initData()
        initListener()
    }

    override fun onStart() {
        super.onStart()
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onStart")
    }

    override fun onResume() {
        super.onResume()
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onResume")
    }

    override fun onPause() {
        super.onPause()
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onPause")
    }

    override fun onStop() {
        super.onStop()
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding = null
        if (isNeedLogLifecycle) LogUtils.logE(TAG, "onDestroy")
    }

    fun requireDataBinding(): Binding {
        return mBinding?: throw NullPointerException("mBinding is null")
    }

    @LayoutRes
    protected abstract fun setLayout(): Int

    protected abstract fun initIntent(savedInstanceState: Bundle?)

    protected abstract fun initView()

    protected abstract fun initData()

    protected abstract fun initListener()

}